package com.baide.sanguanheyi.ct;

import com.baide.sanguanheyi.config.ThreadManager;
import com.baide.sanguanheyi.interfaces.CtCallBack;
import com.baide.sanguanheyi.interfaces.CtSendMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.HashedWheelTimer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class HeartBeatClient implements Runnable, CtSendMsg {
    protected final HashedWheelTimer timer = new HashedWheelTimer();

    private Bootstrap boot;
    @Autowired
    ConnectorIdleStateTrigger idleTriggerHandler;
    @Autowired
    CtConfigClass config;
    @Autowired
    HeartBeatClientHandler heartBeatClientHandler;
    Channel channel;
    ConnectionWatchdog watchdog;
    CtCallBack ctCallBack;
    @Autowired
    XmlUtils xmlUtils;

    public void setCtCallBack(CtCallBack ctCallBack) {
        this.ctCallBack = ctCallBack;
    }

    public void connect() throws Exception {
        heartBeatClientHandler.setCtCallBack(ctCallBack);
        EventLoopGroup group = new NioEventLoopGroup();
        boot = new Bootstrap();
        boot.group(group).channel(NioSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO));

        watchdog = new ConnectionWatchdog(boot, timer, config.getPort(), config.getIp(),
                true, config.getConnectCount(), config.getConnectTime()) {
            @Override
            public ChannelHandler[] handlers() {
                return new ChannelHandler[]{
                        this, // 这里把 ConnectionWatchdog 也添加到了pipeline
                        new IdleStateHandler(60, config.getHeart(), 60, TimeUnit.SECONDS),
                        idleTriggerHandler,
                        new StringDecoder(),
                        new StringEncoder(),
                        heartBeatClientHandler
                };
            }
        };
        ChannelFuture f;
        // 进行连接
        try {
            synchronized (boot) {
                boot.handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(watchdog.handlers());
                    }
                });
                f = boot.connect(config.getIp(), config.getPort());
            }
            channel = f.channel();
            f.sync();
        } catch (Throwable t) {
            throw new Exception("connects to fails", t);
        }
    }

    public void sendMsg(String msg) {
        if (channel == null || !channel.isActive()) channel = watchdog.getChanel();
        if (channel != null) {
            channel.writeAndFlush(msg);
        } else {
            System.out.println("与ct之间的连接断开，请等待重连后继续");
        }

    }

    @Override
    public void run() {
        try {
            connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendBarcode(String code) {
        ThreadManager.getThreadPollProxy().execute(new Runnable() {
            @Override
            public void run() {
                sendMsg(xmlUtils.getBarcodeMessage(code));
            }
        });
    }
}
